const Koa = require("koa");
const Router = require("koa-router");
const views = require("koa-views");
const static = require("koa-static");
const koaBody = require("koa-body");
const fs = require("fs");
let app = new Koa();
let router = new Router();
app.use(koaBody({
    multipart: true // 允许 koabody接收上传的文件
}));
app.use(views(__dirname + "/views"));
app.use(static(__dirname + "/static"));
router.get("/index", async ctx => {
    await ctx.render("index.html");
});

router.get("/product", async ctx => {
    // 文件上传
    await ctx.render("product.html");
});

router.get("/getdata", ctx => {
    // 接收get传递过来的参数
    let data = ctx.query;
    ctx.body = data;
})

router.post("/postdata", ctx => {
    // ctx.body  ---> ctx.response.body
    console.log(ctx.request.body)
        // let str = "";
        // ctx.req.on("data",chunk=>{
        //         str += chunk;
        // })
        // ctx.req.on("end",()=>{
        //     console.log(str);
        // })
    ctx.body = ctx.request.body
})
router.post("/postfile", ctx => {
    // ctx.request.body
    // 接收传递的文件
    console.log(ctx.request.files.myimg.filepath);
    let tempath = ctx.request.files.myimg.filepath;
    let filename = ctx.request.files.myimg.originalFilename;
    if (!fs.existsSync("./static/uploads")) {
        fs.mkdirSync("./static/uploads");
    }
    fs.copyFileSync(tempath, "./static/uploads/" + filename);
    ctx.body = {
        info: "接收了"
    }
})

app.use(router.routes());
app.listen(9999);